#include "ringbuf.h"

void RINGBUF_Init(ringbuf_t* rb, uint8_t* buf, uint16_t size)
{
    rb->buf = buf;
    rb->size = size >> 1;
}

int RINGBUF_Put(ringbuf_t* rb, uint8_t* buf, uint16_t size)
{
    if ((rb->rd + rb->size - rb->wr - 1) % rb->size < size)
        return -1;

    for (int i = 0; i < size; i++)
    {
        rb->buf[rb->wr + rb->size] = rb->buf[rb->wr] = buf[i];
        rb->wr = (rb->wr+1) % rb->size;
    }

    return size;
}

int RINGBUF_Peek(ringbuf_t* rb, uint8_t** buf)
{
    if (rb->rd == rb->wr)
        return 0;

    *buf = &rb->buf[rb->rd];

    return (rb->wr + rb->size - rb->rd) % rb->size;
}

int RINGBUF_Poll(ringbuf_t* rb, uint16_t size)
{
    uint16_t num = (rb->wr + rb->size - rb->rd) % rb->size;

    if (size > num)
        size = num;

    rb->rd = (rb->rd + size) % rb->size;

    return size;
}
